package com.atguigu.tingshu.common.login;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author: atguigu
 * @create: 2024-11-26 09:49
 */
@Slf4j
@Aspect
@Component
public class GuiGuLoginAspect {

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 对所有controller层方法 且 使用自定义注解@GuiGuLogin方法进行增强
     *
     * @param pjp        切入点对象（目标方法对象）
     * @param guiGuLogin 自定义注解对象
     * @return
     * @throws Throwable
     */
    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(guiGuLogin)")
    public Object doBasicProfiling(ProceedingJoinPoint pjp, GuiGuLogin guiGuLogin) throws Throwable {
        log.info("[认证AOP切面]，前置逻辑");
        //一、前置逻辑
        //1. 获取请求对象
        //1.1 通过请求上下文对象获取RequestAttributes(接口)
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //1.2 将接口强转为ServletRequestAttributes(实现类)
        ServletRequestAttributes sra = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = sra.getRequest();
        //2. 从请求头token中获取访问令牌
        String token = request.getHeader("token");
        //3. 根据访问令牌获取用户基本信息。 在此以前登录将用户基本信息存入Redis
        String loginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
        UserInfoVo userInfoVo = (UserInfoVo) redisTemplate.opsForValue().get(loginKey);
        //4. 如果目标方法要求必须登录且Redis中用户信息未查询到，抛出登录异常响应业务状态码208，前端引导用户登录即可
        if (guiGuLogin.required() && userInfoVo == null) {
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        //5. 如果查询Redis用户信息存在，将用户ID存入ThreadLocal
        if (userInfoVo != null) {
            AuthContextHolder.setUserId(userInfoVo.getId());
        }
        //二、执行目标方法-执行目标对象的目标方法(controller层方法)
        Object retVal = pjp.proceed();

        //三、后置逻辑
        log.info("[认证AOP切面]，后置逻辑");
        //6.清理ThreadLocal，避免内存泄漏造成OOM
        AuthContextHolder.removeUserId();
        return retVal;
    }

}
